﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace BF
{
    public class CsvUtil
    {
        public static List<List<string>> LoadCsv(string csvText)
        {
            // split line
            string[] lines = csvText.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);

            if (lines == null || lines.Length == 0)
                return null;

            List<List<string>> result = new List<List<string>>();

            // Parse CVS line. Capture next value in named group: 'val'
            Regex pattern =
                new Regex(@"\s*(?:""(?<val>[^""]*(""""[^""]*)*)""\s*|(?<val>[^,]*))(?:,|$)", RegexOptions.Multiline);
            try
            {
                lines.ForEach((line) => {
                    MatchCollection matchCollection = pattern.Matches(line);
                    List<string> words = new List<string>();
                    for (int i = 0; i < matchCollection.Count; ++i)
                    {
                        string word = matchCollection[i].Groups["val"].Value;
                        words.Add(word);
                    }
                    bool isAllEmpty = words.All(it => string.IsNullOrEmpty(it));
                    if (!isAllEmpty)
                    {
                        result.Add(words);
                    }
                });
            }
            catch (ArgumentException ex)
            {
                Log.W("CsvUtil", $"config parse error! {ex.Message}");
            }

            return result;
        }

        /// <summary>
        /// 行转列
        /// 需要每行的列数一样
        /// </summary>
        public static List<List<string>> Row2Column(List<List<string>> source)
        {
            //行数
            int rowCount = source.Count();
            //列数
            int colCount = source.All(it => it.Count < source[0].Count || string.IsNullOrEmpty(it[source[0].Count - 1]))
                ? source[0].Count - 1 : source[0].Count;

            List<List<string>> result = new List<List<string>>();
            for (int colIndex = 0; colIndex < colCount; ++colIndex)
            {
                List<string> column = new List<string>();
                for (int rowIndex = 0; rowIndex < rowCount; ++rowIndex)
                {
                    column.Add(source[rowIndex][colIndex]);
                }
                result.Add(column);
            }
            return result;
        }
    }
}